package com.tc;

import com.tc.action.FunAction;
import com.tc.action.FunInterface;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerApplication implements Runnable{
    private int port;	//端口号
    private FunInterface fun;	//功能接口，逻辑需要实现
    private Socket socket;	//类内使用的socket
    private ServerSocket server;	//serverSocket
    BufferedReader reader;	//读取对象
    PrintWriter writer;	//输入对象

    /**通过端口和实现了接口的类来实例化一个服务器类
     *
     * @param port 服务端口
     * @param fun	服务逻辑
     */
    public ServerApplication(int port,FunInterface fun) {
        this.port=port;
        this.fun=fun;
    }

    @Override
    public void run() {
        try{
            server=new ServerSocket(port);	//新建serverSocket
            while(true){
                socket=server.accept();	//等待客户端请求
                //dis=new DataInputStream(socket.getInputStream());	//新建一个输入流
                reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String request=reader.readLine();	//从客户端读取数据
                //System.out.println(request);
                String response=fun.deal(request);	//处理客户端发来的数据，并获取处理后的输出
                //dos=new DataOutputStream(socket.getOutputStream());	//新建一个输出流
                //dos.writeUTF(response);	//发送回复到客户端
                //dos.flush();	//每次处理完毕都要关闭相应的端口
                //dos.close();
                //dis.close();
                writer=new PrintWriter(socket.getOutputStream());
                writer.write(response); //输出
                writer.flush();
                reader.close();
                writer.close();
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                server.close();	//关闭响应的端口，防止服务异常停止端口被占用
                socket.close();
                writer.close();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]){
        new Thread(new ServerApplication(10000,new FunAction())).start();//开启服务
        System.out.println("服务端已开启");
    }
}
